import { useEffect, useCallback, useContext } from "react";
import { useLocalStore } from "mobx-react-lite";
// import { useIntl } from "react-intl";
import { useLocalStorage } from "react-use";
import {
    useAppManager,
    useEventBus,
    useAuth,
    useLanguage,
    useMessageBox,
    useFileHandler,
    useAppContainerManager,
    useLogoutExit,
    useWpsPing,
    useShareFn,
    useCopySharedLinkFn,
} from "@anyshare/common/lib/hooks";
import { ipcRenderer, remote, clipboard } from "electron";
import { reaction } from "mobx";
import { IAppContainerOptions, IAppViewRoute } from "@anyshare/common/lib/stores";
import { ElectronEventEmitter } from "@anyshare/common/lib/utils/events/ElectronEventEmitter";
import { ElectronGlobalEventEmitter } from "@anyshare/common/lib/utils/events/ElectronGlobalEventEmitter";
import { BlankWindow } from "./BlankWindow";
import { AppWindow } from "./AppWindow";
import { IOAuth2Token, IDomain } from "@anyshare/common/lib/contexts";
import axios from "axios";
import { osType, isLinux } from "@anyshare/common/lib/utils/platform";
import { useIntl } from "react-intl";
import fs from "fs";
import path from "path";
import openApi from "@anyshare/openapi";
import RichClientLog from "@anyshare/common/lib/utils/logHelper";
import { findDefaultOpenMethod } from "@anyshare/common/lib/utils/extension";
import { ConfigContext } from "@anyshare/common/lib/contexts";
import { toJS } from "mobx";
import {
    MicroWidgetForTaskBarLabel,
    MicroWidgetLabel,
    MicroWidgetDialogLabel,
    MicroWidgetIsFromLibToLibFlag,
    MicroWidgetIsFromKcToKcFlag,
} from "@anyshare/microwidget";
import * as Utils from "../../../common/utils";

interface ILoginedUser {
    [key: string]: string;
}
export interface IMainPageStore {
    windows: AppWindow[];
    blankWindows: BlankWindow[];
    blankWindowsUsed: BlankWindow[];
    domains: IDomain[] | undefined;
    domain: IDomain | undefined;
    newSyncDiskSetting: string[] | undefined;
    syncclientGuide: ILoginedUser | undefined;
}

interface IOpenSyncdisk {
    [key: string]: boolean;
}

interface ISyncDiskName {
    zhcn: string;
    zhtw: string;
    enus: string;
}

const customAxios = axios.create();
const normalRefreshTokenTime: number = 55 * 60 * 1000;
const unnormalRefreshTokenTime: number = 1 * 1000;
let currentTimeout: NodeJS.Timeout;
const log = new RichClientLog();
let refreshTokenLock = false;
let currentOauthToken: IOAuth2Token;

export default function MainPage() {
    const appManager = useAppManager();
    const messagebox = useMessageBox();
    const logoutExit = useLogoutExit();
    const eventBus = useEventBus();
    const fileHandler = useFileHandler();
    const appContainerManager = useAppContainerManager();
    const contextConfig = useContext(ConfigContext);
    const language = useLanguage();
    const auth = useAuth();
    const intl = useIntl();
    const share = useShareFn();
    const copySharedLink = useCopySharedLinkFn();
    const [, setOauth2Token] = useLocalStorage<IOAuth2Token>("oauth2Token");
    const [, setSyncDiskName] = useLocalStorage<ISyncDiskName>("syncDiskName");
    const [openSyncdisk, setOpenSyncdisk] = useLocalStorage<IOpenSyncdisk>("openSyncdisk", {});
    const wpsPingHandler = useWpsPing();
    let [domains] = useLocalStorage<IDomain[]>("domains", []);
    let mainWindowArray: number[] = []; // 用于存放已经打开的主界面的id
    const [syncdiskSetting, setSyncdiskSetting] = useLocalStorage<string[]>("syncdiskSetting", []);
    const [syncclientGuide] = useLocalStorage<ILoginedUser>("syncclientGuide", {});
    eventBus.on("sharedlinkcopyed", (link: string) => {
        clipboard.write({ text: link });
    });
    useEffect(() => {
        const onDirLaunched = async () => {
            const { data } = await openApi.post("/eacp/v1/user/get");
            const userid = data.userid;

            if (userid && openSyncdisk && openSyncdisk[userid]) {
                ipcRenderer.send("launchSyncClient");
            }
        };
        eventBus.on("onDirLaunched", onDirLaunched);
        return () => {
            eventBus.removeListener("onDirLaunched", onDirLaunched);
        };
    }, [openSyncdisk]);

    const store = useLocalStore<IMainPageStore>(() => {
        let domain: IDomain | undefined;

        if (domains?.length && auth.domain) {
            domain = domains.find(({ hostname }) => auth.domain?.hostname === hostname);
        }
        return {
            domain,
            domains,
            blankWindows: [],
            newSyncDiskSetting: [],
            syncclientGuide: syncclientGuide,
            windows: [],
            blankWindowsUsed: [],
        };
    });

    useEffect(() => {
        store.newSyncDiskSetting = syncdiskSetting;
        if (auth.user?.userid) {
            eventBus.emit("newSyncdiskSetting", !!syncdiskSetting?.includes(auth.user?.userid));
        }
    }, [syncdiskSetting]);

    const launchApp = useCallback((route: string | IAppViewRoute, containerOptions?: IAppContainerOptions) => {
        const result = appManager.parse(route);
        if (result) {
            const { app, view, params, query } = result;

            const existWindow = store.windows.filter((window) => {
                const windowsQuery = JSON.parse(JSON.stringify(window.query));
                const appQuery = JSON.parse(JSON.stringify(query));
                if (windowsQuery._tb) {
                    delete windowsQuery._tb;
                }
                if (appQuery._tb) {
                    delete appQuery._tb;
                }

                if (
                    app.name === MicroWidgetForTaskBarLabel ||
                    app.name === MicroWidgetLabel ||
                    app.name === MicroWidgetDialogLabel
                ) {
                    if (app.name === window.app.name) {
                        if (Array.isArray(window.params.microWidget) && Array.isArray(params.microWidget)) {
                            const oldParams = window.params.microWidget.join("");
                            const newParams = params.microWidget.join("");
                            const oldPath = window.query?._path;
                            const newPath = query?._path;
                            const isFromLibraryToLibrary =
                                oldParams.includes(MicroWidgetIsFromLibToLibFlag) &&
                                newParams.includes(MicroWidgetIsFromLibToLibFlag) &&
                                oldParams.includes(MicroWidgetIsFromKcToKcFlag) &&
                                newParams.includes(MicroWidgetIsFromKcToKcFlag);
                            if (oldParams === newParams) {
                                if (isFromLibraryToLibrary) {
                                    return false;
                                }
                                return Boolean(oldPath === newPath);
                            } else {
                                return Boolean(oldParams === newParams);
                            }
                        } else {
                            return Boolean(window.params.microWidget === params.microWidget);
                        }
                    }
                }

                if (app.name === "applist") {
                    if (window.params.appListApp !== params.appListApp) {
                        return false;
                    }
                } else if (
                    Object.keys(query).length > 0 &&
                    window.app.name === app.name &&
                    window.view.path === view.path &&
                    JSON.stringify(windowsQuery) === JSON.stringify(appQuery)
                ) {
                    return true;
                } else if (
                    Object.keys(query).length === 0 &&
                    window.app.name === app.name &&
                    app.name !== "dir" &&
                    window.view.path === view.path
                ) {
                    return true;
                }
                return false;
            });

            if (!view.multiple && existWindow.length > 0) {
                existWindow[0].win.show();

                // 确保窗口显示出来的时候位于最顶层
                existWindow[0].win.setAlwaysOnTop(true);
                existWindow[0].win.setAlwaysOnTop(false);
            } else {
                const fromBlankWindow = store.blankWindows.pop();
                if (fromBlankWindow) {
                    store.blankWindowsUsed.unshift(fromBlankWindow);
                }
                const appWindow = new AppWindow({
                    app,
                    view,
                    params,
                    query,
                    fromBlankWindow,
                    containerOptions,
                });
                store.windows.push(appWindow);
                if (appWindow.app.name === "dir") {
                    mainWindowArray.push(appWindow.id);
                }
                appWindow.win.once("closed", () => {
                    appWindow.win.removeAllListeners();
                    store.windows = store.windows.filter((win) => win.id !== appWindow.id);
                    if (auth.oauth2Token && auth.oauth2Token.access_token === "" && appWindow.app.name === "signin") {
                        ipcRenderer.send("exit");
                    }
                    if (
                        appWindow.app.name === "dir" ||
                        appWindow.app.name === "applist" ||
                        appWindow.app.name === "search" ||
                        appWindow.app.name === MicroWidgetForTaskBarLabel ||
                        appWindow.app.name === MicroWidgetLabel
                    ) {
                        const index = mainWindowArray.indexOf(appWindow.id);
                        if (index > -1) {
                            mainWindowArray.splice(index, 1);
                        }
                    }
                });
                appWindow.win.webContents.on("new-window", async (event, url) => {
                    event.preventDefault();
                    if (url !== "about:blank#blocked" && !url.includes("PowerPointView=SlideShowView")) {
                        await remote.shell.openExternal(url);
                    }
                });

                // ASP-15169【RichClient】【SharedLink】【唤醒】桌面端去除剪切板唤醒功能
                // appWindow.win.on("focus", () => {
                //     if (clipboard.readRTF() && clipboard.readText()) {
                //         const link = clipboard.readRTF();
                //         if (
                //             /^((http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z0-9]{2,5}(:[0-9]{1,5})?(\/)link(\/[a-zA-Z0-9]{34}))*/gm.test(
                //                 link
                //             )
                //         ) {
                //             return;
                //         }
                //     }
                //     var clipboardText = clipboard.readText() || clipboard.readRTF();
                //     const reg = RegExp(
                //         /^((http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z0-9]{2,5}(:[0-9]{1,5})?(\/)link(\/[a-zA-Z0-9]{34}))*/gm
                //     );
                //     const regArr = reg.exec(clipboardText);
                //     var showSharedlinkWin = true;
                //     if (regArr?.length && regArr[0] !== "" && auth.oauth2Token?.access_token && navigator.onLine) {
                //         store.windows.some((window: AppWindow) => {
                //             if (window.app.name === "linkdetect" && window.query.sharedlink === regArr[0]) {
                //                 showSharedlinkWin = false;
                //                 window.win.focus();
                //                 clipboard.clear();
                //                 return true;
                //             }
                //         });
                //         if (showSharedlinkWin) {
                //             launchApp(`linkdetect?_tb=none&sharedlink=${regArr[0]}`);
                //             clipboard.clear();
                //         }
                //     }
                // });

                appWindow.win.webContents.on("did-navigate-in-page", (_event, url) => {
                    const { hash } = new URL(url);
                    const match = /#\/anyshare\/[^/]+\//.exec(hash);
                    if (match) {
                        const appUrl = hash.slice(match[0].length);
                        if (appUrl !== "_blank") {
                            const result = appManager.parse(appUrl);
                            if (result) {
                                appWindow.app = result.app;
                                appWindow.view = result.view;
                                appWindow.params = result.params;
                                appWindow.query = result.query;
                                appWindow.url = appUrl;
                            }
                        }
                    }
                });
            }
        }
    }, []);

    useEffect(() => {
        const mainWindow = remote.getCurrentWindow();
        if (mainWindow.id === 1) {
            remote.BrowserWindow.getAllWindows().forEach((window) => {
                if (window.id !== mainWindow.id) {
                    window.destroy();
                }
            });

            Object.assign(window, { electron: require("electron"), appManager });

            ipcRenderer.on(
                ElectronGlobalEventEmitter.CHANNEL,
                (_event: any, senderId: number, type: string, ...args: any[]) => {
                    store.windows.forEach((window) => {
                        if (!window.win.isDestroyed()) {
                            try {
                                window.send(ElectronGlobalEventEmitter.CHANNEL, senderId, type, ...args);
                            } catch (e) {
                                console.log(e);
                            }
                        }
                    });
                    store.blankWindows.forEach((window) => {
                        if (!window.win.isDestroyed()) {
                            try {
                                window.send(ElectronGlobalEventEmitter.CHANNEL, senderId, type, ...args);
                            } catch (e) {
                                console.log(e);
                            }
                        }
                    });
                }
            );

            ipcRenderer.on(
                ElectronEventEmitter.CHANNEL,
                (_event: any, senderId: number, type: string, ...args: any[]) => {
                    store.windows.forEach((window) => {
                        if (!window.win.isDestroyed()) {
                            try {
                                window.send(ElectronEventEmitter.CHANNEL, senderId, type, ...args);
                            } catch (e) {
                                console.log(e);
                            }
                        }
                    });
                }
            );

            ipcRenderer.on("blankwindowready", (_event: any, windowId: number) => {
                const readyWindow =
                    store.blankWindows.find((win) => win.id === windowId) ||
                    store.blankWindowsUsed.find((win) => win.id === windowId);

                readyWindow?.setReady();
            });

            ipcRenderer.on("appwindowready", (_event: any, windowId: number) => {
                if (store.blankWindowsUsed.findIndex((win) => win.id === windowId) !== -1) {
                    store.blankWindowsUsed = store.blankWindowsUsed.filter((win) => win.id !== windowId);
                }

                const readyWindow = store.windows.find((win) => win.id === windowId);

                readyWindow?.setReady();
            });

            ipcRenderer.on(
                "launchapp",
                (_event: any, route: string | IAppViewRoute, containerOptions?: IAppContainerOptions) =>
                    launchApp(route, containerOptions)
            );

            const handleMainWindows = () => {
                // let alreadyShow:number [] = []
                const allShowedMainWindow = remote.BrowserWindow.getAllWindows().filter((window) => {
                    return mainWindowArray.includes(window.id) && !window.isMinimized();
                });
                if (allShowedMainWindow.length) {
                    for (let i = 0; i < allShowedMainWindow.length; i += 1) {
                        // alreadyShow.push(allShowedMainWindow[i].id);
                        eventBus.emit("AnyShare:showMainWidows", allShowedMainWindow[i].id);
                    }
                } else {
                    if (mainWindowArray.length > 0) {
                        eventBus.emit("AnyShare:showMainWidows", mainWindowArray[mainWindowArray.length - 1]);
                    } else {
                        launchApp("dir");
                    }
                }
            };

            eventBus.on("setWindow", (route: string) => {
                const sliceRoute = (url: string) => {
                    const flag = "/anyshare/";
                    const flagAndLanguageLength = 16;
                    const flagIndex = url.indexOf(flag);
                    return decodeURIComponent(url.slice(flagAndLanguageLength + flagIndex));
                };
                const samePathWindow = remote.BrowserWindow.getAllWindows().filter(
                    (window) => sliceRoute(window.webContents.getURL()) === route
                );

                if (samePathWindow.length !== 0) {
                    samePathWindow[0].show();
                } else {
                    appContainerManager.start(route, {
                        type: "new_tab",
                    });
                }
            });

            ipcRenderer.on("newWindow", (_event: any, mustNewWindows: boolean) => {
                const signinWindow = remote.BrowserWindow.getAllWindows().filter(
                    (window) =>
                        window.webContents.getURL().match("signin") || window.webContents.getURL().match("upgrade")
                );
                if (signinWindow.length !== 0) {
                    signinWindow[0].show();
                } else {
                    if (mustNewWindows) {
                        launchApp("dir");
                    } else {
                        handleMainWindows();
                    }
                }
            });
            ipcRenderer.on("createWindow", () => {
                const signinWindow = remote.BrowserWindow.getAllWindows().filter(
                    (window) =>
                        window.webContents.getURL().match("signin") ||
                        window.webContents.getURL().match("upgrade") ||
                        window.webContents.getURL().match("dir")
                );
                if (signinWindow.length === 0) {
                    launchApp("dir");
                }
            });
            ipcRenderer.on("needLaunchSyncDisk", () => {
                if (auth.oauth2Token?.access_token) {
                    eventBus.emit("launchSyncClient");
                } else {
                    eventBus.once("launchSyncDisk", () => {
                        eventBus.emit("launchSyncClient");
                    });
                }
            });

            ipcRenderer.on("aboutAppVersion", () => {
                launchApp("aboutversion");
            });
            eventBus.on("aboutAppVersion", () => {
                launchApp("aboutversion");
            });

            eventBus.on("openNewMainWindow", () => {
                ipcRenderer.send("mustOpenNewMainWindow");
            });

            eventBus.on("performLogout", () => {
                ipcRenderer.send("performLogout");
            });
            eventBus.on("performExit", () => {
                ipcRenderer.send("performExit");
            });
            const refreshToken = async (oauth2Token: IOAuth2Token, gapTime: number) => {
                if (auth.domain && oauth2Token.refresh_token && oauth2Token.expires_in) {
                    const { hostname, port, https, client_id, client_secret } = auth.domain;
                    if (client_id && client_secret) {
                        refreshTokenLock = true;

                        // 防止处于加锁边界，来回刷新
                        if (
                            currentOauthToken?.expires_in! > oauth2Token?.expires_in &&
                            currentOauthToken?.expires_in! - oauth2Token?.expires_in < 55 * 60 * 1000
                        ) {
                            return;
                        }

                        currentTimeout = setTimeout(async () => {
                            refreshTokenLock = true;
                            const formData = new FormData();

                            formData.append("grant_type", "refresh_token");
                            formData.append("refresh_token", oauth2Token.refresh_token!);
                            await customAxios
                                .post("/oauth2/token", formData, {
                                    baseURL: `${https ? "https:" : "http:"}//${hostname}${port ? `:${port}` : ""}`,
                                    headers: {
                                        Authorization: `Basic ${btoa(
                                            `${encodeURIComponent(client_id)}:${encodeURIComponent(client_secret)}`
                                        )}`,
                                    },
                                })
                                .then(async (res) => {
                                    if (res.data?.expires_in) {
                                        res.data.expires_in += 55 * 60 * 1000 + new Date().getTime();
                                        setOauth2Token(res.data);
                                        currentOauthToken = res.data;
                                        await refreshToken(res.data, normalRefreshTokenTime);
                                        eventBus.emit("succcessRefreshOauth2Token", res.data);
                                        ipcRenderer.send("tokenUpdate", res.data.access_token);
                                        log.info("success tokenRefresh");

                                        setTimeout(() => {
                                            refreshTokenLock = false;
                                            eventBus.emit("unlockRefreshTokenLock");
                                        }, 5 * 1000);
                                    } else {
                                        log.warn("重定向网络下刷新token失败");
                                        // 在重定向网络下，发起通知，停止失败后继续重发
                                        eventBus.emit("electronRefreshingTokenFailed", false);
                                        await refreshToken(oauth2Token, unnormalRefreshTokenTime);
                                    }
                                })
                                .catch(async (err) => {
                                    if (navigator.onLine) {
                                        log.error(err);
                                    }
                                    if (err.response?.status === 400) {
                                        // refreshtoken失效后，刷新token失败，弹框提示
                                        eventBus.emit("electronAuthException", 401001001);
                                        // 通知正在进行的网络请求，停止失败后继续重发
                                        eventBus.emit("electronRefreshingTokenFailed", false);
                                    } else {
                                        await refreshToken(oauth2Token, unnormalRefreshTokenTime);
                                    }
                                });
                        }, gapTime);
                    }
                }
            };

            const checkVersion = async () => {
                try {
                    let package_type = "";
                    if (isLinux) {
                        if (remote.app.getPath("exe").match("/tmp/.mount")) {
                            package_type = "AppImage";
                        } else {
                            if (fs.existsSync("/etc/debian_version")) {
                                //在debian中
                                package_type = "deb";
                            } else {
                                //在redhat中
                                package_type = "rpm";
                            }
                        }
                    }
                    const { data } = await (openApi as any).get(
                        package_type
                            ? `/deploy-manager/client/version/${osType}_${package_type}/${remote.app
                                  .getVersion()
                                  .split("-")
                                  .join(".")}`
                            : `/deploy-manager/client/version/${osType}/${remote.app.getVersion().split("-").join(".")}`
                    );
                    if (data.version !== "-1") {
                        launchApp("upgrade");
                    } else {
                        launchApp("dir");
                        ipcRenderer.send("handleArgsAfterLaunch");
                        eventBus.emit("onDirLaunched");
                        const files = fs.readdirSync(remote.app.getPath("userData"));
                        files.forEach((file) => {
                            if (path.extname(file) === ".exe" || path.extname(file) === ".dmg") {
                                try {
                                    fs.unlinkSync(path.resolve(remote.app.getPath("userData"), file));
                                } catch (error) {
                                    log.info("Delete Install Package Failed");
                                }
                            }
                        });
                    }
                } catch (error) {
                    //检查升级失败
                    launchApp("dir");
                    ipcRenderer.send("handleArgsAfterLaunch");
                    log.warn(error);
                }
            };
            eventBus.on("oauth2token", async (oauth2Token: any) => {
                currentOauthToken = oauth2Token;
                await refreshToken(oauth2Token, normalRefreshTokenTime);
                log.info("login success");
                checkVersion();
                setTimeout(() => {
                    launchApp("syncdetails");
                }, 500);
            });

            eventBus.on("refreshOauth2Token", async (oauth2Token: any) => {
                if (!refreshTokenLock) {
                    // 清掉刷新token计时器，手动再次出发先的刷新
                    refreshTokenLock = true;
                    // 防止处于加锁边界，来回刷新
                    if (
                        currentOauthToken?.expires_in! > oauth2Token?.expires_in &&
                        currentOauthToken?.expires_in! - oauth2Token?.expires_in < 55 * 60 * 1000
                    ) {
                        return;
                    }
                    clearTimeout(currentTimeout);
                    await refreshToken(oauth2Token, 0);
                }
            });

            eventBus.on("skipUpgrade", () => {
                launchApp("dir");
                ipcRenderer.send("handleArgsAfterLaunch");
                eventBus.emit("onDirLaunched");
            });

            const querryNetworkStatus = async (id: number) => {
                if (!window.navigator.onLine) {
                    eventBus.emit("AnyShare:NoNetworkStatus", id);
                    return;
                }
                if (auth.domain) {
                    const { hostname, port, https } = auth.domain;
                    try {
                        let res = await openApi.post("/eacp/v1/ping" as any, undefined, {
                            https,
                            hostname,
                            port,
                        });
                        if (res?.data !== "ok") {
                            eventBus.emit("AnyShare:NoNetworkStatus", id);
                            return;
                        }
                    } catch (e) {
                        log.error(e);
                        if (!navigator.onLine || !e?.response) {
                            eventBus.emit("AnyShare:NoNetworkStatus", id);
                            return;
                        }
                    }
                }
            };

            eventBus.on("AnyShare:QuerryNetWorkStatus", async (id: any) => {
                querryNetworkStatus(id);
            });

            eventBus.on("syncdiskPopoverClick", () => {
                if (auth.user?.userid) {
                    if (!store.syncclientGuide) {
                        store.syncclientGuide = {};
                    }
                    store.syncclientGuide[auth.user?.userid] = auth.domain?.hostname!;
                }
            });
            eventBus.on("syncClientOpen", (docid: string, gnsPath: string, selecFile: number) => {
                ipcRenderer.send("syncClientOpen", docid, gnsPath, selecFile);
            });
            eventBus.on("syncClientOpenDir", (docid: string, gnsPath: string) => {
                ipcRenderer.send("syncClientOpenDir", docid, gnsPath);
            });
            eventBus.on("changeLanguage", (language: any) => {
                ipcRenderer.send("changeLanguage", language);
            });
            ipcRenderer.on("startSyncDisk", (_event: any, window: string) => {
                if (auth.user?.userid && !store.newSyncDiskSetting?.includes(auth.user?.userid)) {
                    const list = [...store.newSyncDiskSetting, auth.user?.userid];
                    setSyncdiskSetting(list);
                }

                ipcRenderer.send("login", auth.domain?.hostname, auth.domain?.port, auth.oauth2Token?.access_token);
                ipcRenderer.send("onLogined", auth.oauth2Token?.access_token);
                if (window !== "openCache") {
                    ipcRenderer.send("waitUntilSyncClientOnline", window);
                }
            });
            ipcRenderer.on("setSyncDiskLaunchOption", (_event: any, autoLaunch: boolean) => {
                if (auth.user?.userid) {
                    const options = {
                        ...openSyncdisk,
                        ...{ [auth.user?.userid]: autoLaunch },
                    };
                    setOpenSyncdisk(toJS(options));
                }
            });
            ipcRenderer.on("syncdiskVersionConflict", async (_event: any) => {
                //弹窗提示同步盘冲突
                await messagebox({
                    type: "info",
                    title: intl.formatMessage({ id: "syncclient.launchfailed" }),
                    message: intl.formatMessage({ id: "syncclient.uninstalloldversion" }),
                });
            });
            const checkCsfLevel = (docid: string) => {
                return Promise.all([
                    openApi.post("/eacp/v1/user/get"),
                    openApi.post("/efast/v1/file/attribute", { docid }),
                ]).then(([userinfo, docinfo]) => {
                    return userinfo.data.csflevel >= docinfo.data.csflevel;
                });
            };
            ipcRenderer.on("syncdiskOpenInRichclient", async (_event: any, docId: string, fromWebDir?: boolean) => {
                try {
                    const {
                        data: { result },
                    } = await openApi.post("/eacp/v1/perm1/check", { docid: docId, perm: "display" });
                    if (!result) {
                        await checkCsfLevel(docId);
                        const { data } = await openApi.get("/efast/v1/entry-doc-lib");
                        const itemType = data?.find((items: any) => items.id === docId)?.type;
                        const getType = (itemType: any) => {
                            switch (itemType) {
                                case "user_doc_lib":
                                    return "user";
                                case "department_doc_lib":
                                    return "department";
                                case "custom_doc_lib":
                                    return "custom";
                                case "shared_user_doc_lib":
                                    return "shared_user";
                            }
                        };

                        const docidNoGns = docId.replace("gns://", "");
                        const fdocid = docidNoGns.substring(0, docidNoGns.lastIndexOf("/"));
                        const fileDocid = docidNoGns.substring(docidNoGns.lastIndexOf("/") + 1);
                        if (fdocid.length === 0) {
                            const container = appContainerManager.start(`dir/${getType(itemType)}?sel=${fileDocid}`, {
                                type: "new_tab",
                            });
                            container?.focus();
                            container?.show();
                        } else {
                            const container = appContainerManager.start(
                                fromWebDir ? `dir/${docidNoGns}` : `dir/${fdocid}?sel=${fileDocid}`,
                                {
                                    type: "new_tab",
                                }
                            );
                            container?.focus();
                            container?.show();
                        }
                    } else {
                        await messagebox({
                            type: "info",
                            title: intl.formatMessage({ id: "explorerlocation.no" }),
                            message: intl.formatMessage({ id: "explorerlocation.noAuthority" }),
                        });
                    }
                } catch (err) {
                    if (err && err.response) {
                        const { data } = err.response;
                        if (data.code === 403002065) {
                            await messagebox({
                                type: "info",
                                title: "language.tips",
                                message: intl.formatMessage({
                                    id: `err.403002065.linkdetect`,
                                }),
                            });
                            return;
                        }
                    }
                    await messagebox({
                        type: "info",
                        title: intl.formatMessage({ id: "explorerlocation.no" }),
                        message: intl.formatMessage({ id: "err.404002006.detailPanel" }),
                    });
                }
            });

            ipcRenderer.on("downloadSubDocument", (_event: any, msg: string) => {
                eventBus.emit("AnyShare:RichClientdownload", msg);
            });

            ipcRenderer.on("syncdiskInvokeShare", (_event: any, msg: any) => {
                share({ docid: msg.docid, name: msg.name, size: msg.size }, msg.type, msg.isAnony);
            });
            ipcRenderer.on("syncdiskInvokeCopySharedLink", (_event: any, msg: any) => {
                copySharedLink({ docid: msg.docid, name: msg.name, size: msg.size });
            });
            ipcRenderer.on("syncDiskFilePreview", async (_event: any, msg: string) => {
                const item = JSON.parse(msg);
                await contextConfig.loadUrlConfig({ id: item?.docid, service: "office_online" });
                const hasOfficeOnline = contextConfig?.urlConfig?.hasOfficeOnline;
                const hasWps = await wpsPingHandler();
                const openMethod = findDefaultOpenMethod(item.name, hasOfficeOnline, hasWps);
                const Handler = fileHandler.getFileHandler(item, openMethod);
                new Handler({ appContainerManager }).open(item, { latest: true });
            });

            eventBus.on("launchSyncClient", () => {
                ipcRenderer.send("launchSyncClient");
            });

            ipcRenderer.on("launchofficeonline", (_event: any, { url, id }: { url: string; id: number }) => {
                remote.BrowserWindow.fromId(Number(id))?.destroy();
                launchApp(url);
            });

            ipcRenderer.on("launchWithParams", async (_event: any, msg: any) => {
                if (msg.client === "richclient") {
                    if (msg.route?.startsWith("dir/")) {
                        ipcRenderer.emit("syncdiskOpenInRichclient", null, msg.docid, msg.type === "folder");
                    } else {
                        const kcOpenurl = msg.sel ? `${msg.route}&sel=${msg.sel}` : msg.route;
                        const container = appContainerManager.start(kcOpenurl, {
                            type: "new_tab",
                        });
                        container?.focus();
                        container?.show();
                    }
                } else {
                    //检测同步盘是否配置了缓存
                    const onSyncdiskConfigChecked = async () => {
                        log.info("onSyncdiskConfigChecked");
                        try {
                            const {
                                data: { namepath },
                            } = await openApi.post("/efast/v1/file/convertpath", {
                                docid: msg.docid,
                            });
                            if (msg.type === "file") {
                                ipcRenderer.send("syncClientOpen", msg.docid, namepath, 1);
                            } else {
                                ipcRenderer.send("syncClientOpenDir", msg.docid, namepath);
                            }
                        } catch (error) {
                            if (error && error.response) {
                                const { data } = error?.response;
                                if (data) {
                                    switch (data.code) {
                                        //请求的文件或目录不存在
                                        case 404002006:
                                        case 403001171:
                                            await messagebox({
                                                type: "info",
                                                title: "language.tips",
                                                message: intl.formatMessage({
                                                    id: `err.${data.code}.linkdetect`,
                                                }),
                                            });
                                            break;
                                        case 403001002:
                                            await messagebox({
                                                type: "info",
                                                title: "language.tips",
                                                message: intl.formatMessage({
                                                    id: "err.403001002.checksize",
                                                }),
                                            });
                                            break;
                                        case 403002065:
                                            await messagebox({
                                                type: "info",
                                                title: "language.tips",
                                                message: intl.formatMessage({
                                                    id: `err.403002065.linkdetect`,
                                                }),
                                            });
                                            break;
                                    }
                                }
                            }
                        }
                    };
                    const {
                        data: { userid },
                    } = await openApi.post("/eacp/v1/user/get");
                    log.info(
                        `store.newSyncDiskSetting?.includes(auth.user?.userid || userid)的值${store.newSyncDiskSetting?.includes(
                            auth.user?.userid || userid
                        )}`
                    );
                    if (store.newSyncDiskSetting?.includes(auth.user?.userid || userid)) {
                        //配置过
                        onSyncdiskConfigChecked();
                    } else {
                        try {
                            let messageStr: string;
                            const syncDiskName = Utils.getSyncDiskName();
                            if (language.language === "en-us") {
                                messageStr = intl.formatMessage({ id: `electron.syncdiskconfigempty` });
                            } else {
                                messageStr = intl.formatMessage(
                                    { id: "electron.syncdiskconfigempty" },
                                    {
                                        syncDiskName:
                                            language.language === "zh-cn" ? syncDiskName.zhcn : syncDiskName.zhtw,
                                    }
                                );
                            }
                            if (store.syncclientGuide && store.syncclientGuide[userid]) {
                                log.info(`syncclientGuide[userid] = true}`);
                                await messagebox({
                                    type: "confirm",
                                    title: intl.formatMessage({ id: "language.tips" }),
                                    message: messageStr,
                                    okText: intl.formatMessage({ id: `electron.setconfig` }),
                                    cancelText: intl.formatMessage({ id: `recycle.size.close` }),
                                });
                                ipcRenderer.send("launchSyncClient");
                            }
                        } catch (e) {
                            console.log(e);
                        }
                    }
                }
            });
            launchApp("signin?_tb=none");
        } else {
            mainWindow.destroy();
        }
    }, []);

    useEffect(() => {
        const onAuthException = async (errorCode: number) => {
            // 清除刷新token的计时器
            clearTimeout(currentTimeout);
            refreshTokenLock = false;
            try {
                store.windows.forEach((window) => {
                    try {
                        window.win.destroy();
                    } catch (_e) {
                        log.error(`${window.app?.name} close failed`);
                    }
                });

                await logoutExit({
                    type: "info",
                    title: intl.formatMessage({ id: `err.${errorCode}.electron` }),
                });

                if (auth.oauth2Token?.access_token) {
                    const oauth2ExitWindow = new remote.BrowserWindow({ show: false });
                    oauth2ExitWindow.loadURL(
                        `${auth.domain?.https ? "https:" : "http:"}//${auth.domain?.hostname}${
                            auth.domain?.port ? `:${auth.domain.port}` : ""
                        }/oauth2/sessions/logout?id_token_hint=${
                            auth.oauth2Token.id_token || ""
                        }&state=${encodeURIComponent(
                            btoa(JSON.stringify({ windowId: remote.getCurrentWindow().id }))
                        )}&post_logout_redirect_uri=${encodeURIComponent("anyshare://oauth2/logout/callback")}`
                    );
                }
                setOauth2Token({} as IOAuth2Token);
                eventBus.emit("clearLoginToken");
                eventBus.once("electronAuthException", onAuthException);
                ipcRenderer.send("reLanuch");
            } catch (e) {
                eventBus.once("electronAuthException", onAuthException);
                ipcRenderer.send("reLanuch");
            }
        };
        eventBus.once("electronAuthException", onAuthException);
        const onRegisterThirdlogin = (url: string) => {
            eventBus.once("removeThirdloginCookies", () => {
                remote.session.defaultSession.clearStorageData({ origin: url, storages: ["cookies"] });
            });
        };
        eventBus.once("registerThirdlogin", onRegisterThirdlogin);
        const onLogout = async () => {
            try {
                await logoutExit({
                    type: "confirm",
                    title: intl.formatMessage({ id: "logoutClientNow" }),
                });

                ipcRenderer.send("cancleAnyShareLayout", false);
                ipcRenderer.send("cancleAnyShareExit", false);
                // 清除刷新token的计时器
                clearTimeout(currentTimeout);
                refreshTokenLock = false;
                store.windows.forEach((window) => {
                    try {
                        if (window.query.title !== intl.formatMessage({ id: "logoutClientNow" })) {
                            window.win.destroy();
                        }
                    } catch {
                        log.error(`${window.app?.name} close failed`);
                    }
                });

                if (auth.oauth2Token?.access_token) {
                    const oauth2ExitWindow = new remote.BrowserWindow({ show: false });
                    oauth2ExitWindow.loadURL(
                        `${auth.domain?.https ? "https:" : "http:"}//${auth.domain?.hostname}${
                            auth.domain?.port ? `:${auth.domain.port}` : ""
                        }/oauth2/sessions/logout?id_token_hint=${
                            auth.oauth2Token.id_token || ""
                        }&state=${encodeURIComponent(
                            btoa(JSON.stringify({ windowId: remote.getCurrentWindow().id }))
                        )}&post_logout_redirect_uri=${encodeURIComponent("anyshare://oauth2/logout/callback")}`
                    );
                    setOauth2Token({} as IOAuth2Token);
                    eventBus.emit("clearLoginToken");
                    ipcRenderer.send("reLanuch");
                    setTimeout(() => {
                        oauth2ExitWindow.close();
                    }, 5000);
                } else {
                    ipcRenderer.send("reLanuch");
                }
                // alert("noerror")
                //第三方登录
                if (auth.user?.usertype == 3) {
                    eventBus.emit("removeThirdloginCookies");
                    eventBus.once("registerThirdlogin", onRegisterThirdlogin);
                }
            } catch (e) {
                ipcRenderer.send("cancleAnyShareLayout", false);
                eventBus.once("reLanuch", onLogout);
            }
        };
        ipcRenderer.on("trayLogOut", onLogout);
        ipcRenderer.on("afterRelaunch", () => {
            launchApp("signin?_tb=none");
        });
        const onDirectExit = () => {
            try {
                ipcRenderer.send("cancleAnyShareExit", false);
                ipcRenderer.send("cancleAnyShareLayout", false);
                // 清除刷新token的计时器
                clearTimeout(currentTimeout);
                refreshTokenLock = false;
                store.windows.forEach((window) => {
                    try {
                        window.win.destroy();
                    } catch (_e) {
                        log.error(`${window.app?.name} close failed`);
                    }
                });
                setOauth2Token({} as IOAuth2Token);
                // eventBus.emit("clearLoginToken");
                ipcRenderer.send("exit");
            } catch (e) {
                ipcRenderer.send("exit");
            }
        };
        const onExit = async () => {
            try {
                await logoutExit({
                    type: "confirm",
                    title: intl.formatMessage({ id: "exitClientNow" }),
                });

                ipcRenderer.send("cancleAnyShareExit", false);
                ipcRenderer.send("cancleAnyShareLayout", false);
                // 清除刷新token的计时器
                clearTimeout(currentTimeout);
                refreshTokenLock = false;
                store.windows.forEach((window) => {
                    try {
                        window.win.destroy();
                    } catch (_e) {
                        log.error(`${window.app?.name} close failed`);
                    }
                });
                setOauth2Token({} as IOAuth2Token);
                eventBus.emit("clearLoginToken");
                ipcRenderer.send("exit");
            } catch (e) {
                ipcRenderer.send("cancleAnyShareExit", false);
                eventBus.once("exit", onExit);
            }
        };
        ipcRenderer.on("trayExit", onExit);
        ipcRenderer.on("trayExitWithout", onDirectExit);
        eventBus.once("exit", onExit);
        ipcRenderer.on("stopExecution", () => {
            messagebox({ type: "info", title: intl.formatMessage({ id: "syncclientBlockExit" }) });
        });
        ipcRenderer.on("focusExitMsgBox", () => {
            eventBus.emit("AnyShare:exitMsgBoxShow");
        });
        ipcRenderer.on("focusLogoutMsgBox", () => {
            eventBus.emit("AnyShare:logoutMsgBoxShow");
        });
        return () => {
            eventBus.removeListener("electronAuthException", onAuthException);
            ipcRenderer.removeListener("trayLogOut", onLogout);
            eventBus.removeListener("exit", onExit);
            ipcRenderer.removeListener("trayExit", onExit);
        };
    }, [intl]);

    useEffect(
        () =>
            reaction(
                () => [auth.oauth2Token?.refresh_token],
                () => {
                    if (auth.oauth2Token?.refresh_token) {
                        console.log(auth.oauth2Token.refresh_token);
                    }
                }
            ),
        []
    );

    useEffect(
        () =>
            reaction(
                () => [store.blankWindows.length],
                () => {
                    if (store.blankWindows.length < 3) {
                        store.blankWindows.unshift(new BlankWindow());
                    }
                },
                {
                    fireImmediately: true,
                    delay: 100,
                }
            ),
        []
    );

    useEffect(() => {
        setOauth2Token({} as IOAuth2Token);
        const syncDiskName = Utils.getSyncDiskName();
        ipcRenderer.send("currentLanguage", language.language, store.domain ? true : false);
        setSyncDiskName(syncDiskName); // 保存同步盘的名字
    }, []);
    return null;
}
